package cn.bbstone.pisces2.server.handler;

import cn.bbstone.pisces2.comm.BFileCmd;
import cn.bbstone.pisces2.proto.req.ReqFile;
import cn.bbstone.pisces2.server.cache.FileDataCacheItem;
import cn.bbstone.pisces2.server.cache.ServerCache;
import cn.bbstone.pisces2.server.util.MsgUtil;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ReqFileDataAckHandler implements ServerHandler {
    private static Logger log = LoggerFactory.getLogger(ReqFileDataAckHandler.class);

    public ReqFileDataAckHandler() {
    }

    @Override
    public void handle(ChannelHandlerContext ctx, ReqFile reqFile) {
//        long fileNo = reqFile.getFileNo();
//        log.info("file(with fielNo: {}) information success recv by client.", fileNo);
        // TODO setup reqFileData recv timeout, if timeout not recv this msg, try to resend reqFileData


        // TODO check if all chunks send, then remove cacheItem in ServerCache
        long fileNo = reqFile.getFileNo();
        FileDataCacheItem cacheItem = ServerCache.get(fileNo);
        log.debug("file data ack, fileNo: {}, chunks: {}, chunkNo: {}", fileNo, cacheItem.getChunks(), cacheItem.getChunkNo());
        // all file data chunks have been sent, remove cacheItem
        // when the file is empty file, chunks =0, chunkNo = 1
        if (cacheItem.getChunks() <= cacheItem.getChunkNo()) {
            MsgUtil.closeServerFis(cacheItem);
            ServerCache.remove(cacheItem.getFileNo());
            log.debug("now (FileDataCacheItem)serverCache.size: {}", ServerCache.size());
        } else { // send next chunk
            log.debug("-->-->--> fileNo: {}, chunkNo/chunks: {}/{}.", fileNo, cacheItem.getChunkNo(), cacheItem.getChunks());
            MsgUtil.sendFileData(ctx, BFileCmd.RSP_FILE_DATA, fileNo, reqFile.getReqTs());
        }

    }


}
